<template>
    <view class="chatInterface" @contextmenu.prevent="">
        <view class="chat-box" v-if="!firstChat">
            <view class="scroll-view">
                <image v-if="history.loading" class="history-loaded" src="/static/images/loading.svg" />
                <view v-else :class="history.allLoaded ? 'history-loaded' : 'load'" @click="loadHistoryMessage(false)">
                    <view>{{ history.allLoaded ? '已经没有更多的历史消息' : '点击获取历史消息' }}</view>
                </view>

                <view class="message-tip" v-if="!firstChat && !canSendMessage">
                    <image class="tip-icon" src="https://hxs.dsjhs.com:553/prod-api/profile/wxts-icon.png" mode="">
                    </image>
                    <text>对方未回复你之前，只能发送一条消息</text>
                </view>

                <checkbox-group @change="selectMessages">
                    <!--消息记录-->
                    <view v-for="(message, index) in history.messages" :key="message.messageId">
                        <!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
                        <view class="time-lag c343">
                            {{ renderMessageDate(message, index) }}
                        </view>
                        <view class="message-recalled" v-if="message.recalled">
                            <view v-if="message.senderId !== currentUser.userId">{{ friend.name }}撤回了一条消息</view>
                            <view v-else class="message-recalled-self">
                                <view>你撤回了一条消息</view>
                                <span v-if="message.type == 'text' && Date.now() - message.timestamp < 60 * 1000"
                                    @click="editRecalledMessage(message.payload.text)">重新编辑</span>
                            </view>
                        </view>
                        <view class="message-item" v-else>
                            <view class="message-item-checkbox">
                                <checkbox v-show="messageSelector.visible && message.status !== 'sending'"
                                    borderColor="#FFDE6D" color="#111" :value="message.messageId"
                                    :checked="messageSelector.messages.includes(message)" />
                            </view>
                            <view class="message-item-content" :class="{ 'self': message.senderId == currentUser.userId }">
                                <view class="avatar">
                                    <image
                                        :src="message.senderId == currentUser.userId ? (api_host + currentUser.userAvatar) : (api_host + friend.userAvatar)">
                                    </image>
                                </view>

                                <view class="content" @click.right="showActionPopup(message)"
                                    @longpress="showActionPopup(message)">
                                    <view class="message-payload" style="margin-left: 12px;">
                                        <b class="pending" v-if="message.status == 'sending'"></b>
                                        <b class="send-fail" v-if="message.status == 'fail'"></b>
                                        <view v-if="message.type == 'text'" v-html="renderTextMessage(message)"></view>
                                        <image v-if="message.type == 'image'" :data-url="message.payload.url"
                                            :src="message.payload.url"
                                            :style="{ height: getImageHeight(message.payload.width, message.payload.height) + 'rpx' }"
                                            class="image-content" mode="heightFix" @click="showImageFullScreen"></image>
                                        <image v-if="message.type == 'img'" :data-url="message.payload.url"
                                            :src="api_host + message.payload.url" :style="{ height: '200rpx' }"
                                            class="image-content" mode="heightFix" @click="showImageFullScreen"></image>
                                        <view v-if="message.type == 'order'" class="order-content">
                                            <view class="order-id">订单号1：{{ message.payload.id }}</view>
                                            <view class="order-body">
                                                <image :src="message.payload.url" class="order-img"></image>
                                                <view>
                                                    <view class="order-name">{{ message.payload.name }}</view>
                                                    <view class="order-info">
                                                        <view class="order-price">{{ message.payload.price }}</view>
                                                        <view class="order-count">共{{ message.payload.count }}件</view>
                                                    </view>
                                                </view>
                                            </view>
                                        </view>
                                        <view class="pet-msg" v-if="message.type == 'pet'"
                                            @click="nologinJump('/subpage/pet/detail?id=' + message.payload.id)">
                                            <view class="bgFff box_shadow item radius30 overflow-hidden">
                                                <view class="pet-img pore">
                                                    <image :src="api_host + message.payload.icon" mode="widthFix"
                                                        style="width: 300rpx;"></image>
                                                </view>
                                                <view class="p20 c343 f26">{{ message.payload.petName }}</view>
                                            </view>
                                        </view>
                                    </view>
                                    <view v-if="message.senderId == currentUser.userId"
                                        :class="message.read ? 'message-read' : 'message-unread'">
                                        <view v-if="message.status == 'success'">{{ message.read ? '已读' : '未读' }}</view>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </checkbox-group>
            </view>
            <view class="action-box" v-if="!videoPlayer.visible && !messageSelector.visible">
                <view class="flex-jus mb20 mr20" v-if="showPet">
                    <text></text>
                    <view class="">
                        <u-button color="#FFDE6D" :customStyle="{ 'color': '#111', 'height': '80rpx', 'width': '100%' }"
                            shape="circle" @click="sendpetMessage">发送宠物档案</u-button>
                    </view>
                </view>
                <view class="bgFff">
                    <view class="action-top">
                        <!-- #ifdef H5 -->
                        <input v-model="text" @confirm="sendTextMessage"
                            @focus="otherTypesMessagePanelVisible = false, emoji.visible = false"
                            class="consult-input c343" :disabled="!canSendMessage" maxlength="700"
                            :placeholder="canSendMessage ? '请输入内容' : '对方未回复，暂时无法发送消息'" type="text" />
                        <!-- #endif -->
                        <!-- #ifdef MP-WEIXIN -->
                        <input v-model="text" @confirm="sendTextMessage"
                            @focus="otherTypesMessagePanelVisible = false, emoji.visible = false"
                            class="consult-input c343" :disabled="!canSendMessage" maxlength="700"
                            :placeholder="canSendMessage ? '请输入内容' : '对方未回复，暂时无法发送消息'" type="text" />
                        <!-- #endif -->
                        <view @click="switchEmojiKeyboard" :class="{ 'disabled': !canSendMessage }">
                            <image class="more" v-if="emoji.visible" src="/static/images/jianpan.png"></image>
                            <image class="more" v-else src="/static/images/emoji.png"></image>
                        </view>
                        <view :class="{ 'disabled': !canSendMessage }">
                            <image @click="canSendMessage && showOtherTypesMessagePanel()" class="more"
                                src="/static/images/more.png" />
                        </view>
                        <view v-if="text && canSendMessage" class="send-btn-box">
                            <text class="btn" @click="sendTextMessage()">发送</text>
                        </view>
                    </view>
                    <!--展示表情列表-->
                    <view class="action-bottom action-bottom-emoji" v-if="emoji.visible">
                        <image class="emoji-item" v-for="(emojiItem, emojiKey, index) in emoji.map" :key="index"
                            :src="emoji.url + emojiItem" @click="chooseEmoji(emojiKey)"></image>
                    </view>
                    <!--其他类型消息面板-->
                    <view v-if="otherTypesMessagePanelVisible" class="action-bottom">
                        <view class="more-icon">
                            <image @click="sendImageMessage()" class="operation-icon" src="/static/images/picture.png">
                            </image>
                            <view class="operation-title">图片</view>
                        </view>
                        <!-- <view class="more-icon">
						<image @click="showOrderMessageList()" class="operation-icon" src="/static/images/order.png">
						</image>
						<view class="operation-title">宠物</view>
					</view> -->
                    </view>
                </view>
            </view>
            <view class="action-popup" @touchmove.stop.prevent v-if="actionPopup.visible">
                <view class="layer"></view>
                <view class="action-list">
                    <view class="action-item" @click="deleteSingleMessage">删除</view>
                    <view class="action-item" v-if="actionPopup.recallable" @click="recallMessage">撤回</view>
                    <view class="action-item" @click="showCheckBox">多选</view>
                    <view class="action-item" @click="hideActionPopup">取消</view>
                </view>
            </view>
            <view class="messageSelector-box" v-if="messageSelector.visible">
                <view class="textC mr30" @click="allCheckbox">
                    <view>
                        <u-icon name="checkmark-circle" color="#34314F" size="30"></u-icon>
                    </view>
                    <view class="f28 c343">全选</view>
                </view>
                <view class="textC mr30 ml30" @click="deleteMultipleMessages">
                    <view>
                        <u-icon name="trash" color="#34314F" size="30"></u-icon>
                    </view>
                    <view class="f28 c343">删除</view>
                </view>
                <view class="textC ml30" @click="hideCheckBox">
                    <view>
                        <u-icon name="close-circle" color="#34314F" size="28"></u-icon>
                    </view>
                    <view class="f28 c343">取消</view>
                </view>
            </view>
            <view class="record-loading" v-if="audio.recording"></view>
            <video v-if="videoPlayer.visible" :src="videoPlayer.url" id="videoPlayer"
                @fullscreenchange="onVideoFullScreenChange"></video>
        </view>

        <view class="first-chat" v-else>
            <view class="block_2 flex-col">
                <text class="text_3">向TA发送一条打招呼</text>
                <view class="chat-list">
                    <view v-for="(item, index) in currentChatList" :key="index" class="text-wrapper_1 flex-col"
                        :class="{ 'active-chat': id == item.id }" @click="handleSelectChatItem(item)">
                        <text class="text_4">
                            {{ item.text }}
                        </text>
                    </view>
                </view>

                <view class="box_3 flex-row justify-between">
                    <view class="text-wrapper_6 flex-col" @click="handleBack">
                        <text class="text_9">再等等</text>
                    </view>
                    <view class="text-wrapper_7 flex-col" @click="handleSend">
                        <text class="text_10">发送</text>
                    </view>
                </view>
                <image class="image_3" referrerpolicy="no-referrer"
                    src="https://hxs.dsjhs.com:553/prod-api/profile/dazhaohu-bg.png" />
            </view>
        </view>
    </view>
</template>

<script>
import {
    getUserinfobyid
} from '@/common/api_user.js'
import {
    getPetinfo
} from '@/common/api_pet.js'
import EmojiDecoder from '@/lib/EmojiDecoder';
import {
    getPersonInfo,
} from '@/common/api_meethuangshi.js'
import {
    formatDate
} from '@/lib/utils';
const IMAGE_MAX_WIDTH = 200;
const IMAGE_MAX_HEIGHT = 150;
const recorderManager = uni.getRecorderManager();
export default {
    name: 'privateChat',
    data() {
        const emojiUrl = 'https://imgcache.qq.com/open/qcloud/tim/assets/emoji/';
        const emojiMap = {
            '[么么哒]': 'emoji_3@2x.png',
            '[乒乓]': 'emoji_4@2x.png',
            '[便便]': 'emoji_5@2x.png',
            '[信封]': 'emoji_6@2x.png',
            '[偷笑]': 'emoji_7@2x.png',
            '[傲慢]': 'emoji_8@2x.png',
            '[微笑]': 'emoji_9@2x.png',
            '[微笑1]': 'emoji_10@2x.png',
            '[微笑2]': 'emoji_11@2x.png',
            '[微笑3]': 'emoji_12@2x.png',
            '[微笑5]': 'emoji_14@2x.png',
            '[微笑6]': 'emoji_15@2x.png',
            '[微笑7]': 'emoji_16@2x.png',
            '[微笑8]': 'emoji_17@2x.png',
            '[微笑9]': 'emoji_18@2x.png'
        };
        return {
            friendId: '',
            firstChat: false,
            //聊天文本框
            text: '',
            friend: {},
            to: {}, // 作为createMessage的参数
            currentUser: null,

            // 消息发送限制相关状态
            hasUnrepliedMessage: false, // 是否有未回复的消息
            lastSentMessageId: null, // 最后发送的消息ID
            canSendMessage: true, // 是否可以发送消息

            // 聊天类型：default-默认搭子聊天, activity-活动聊天, pending-待审核聊天, success-审核成功聊天
            chatType: 'default',

            //定义表情列表
            emoji: {
                url: emojiUrl,
                map: emojiMap,
                visible: true,
                decoder: new EmojiDecoder(emojiUrl, emojiMap),
            },
            //是否展示'其他消息类型面板'
            otherTypesMessagePanelVisible: true,
            orderList: {
                orders: [],
                visible: false
            },
            history: {
                messages: [],
                allLoaded: false,
                loading: false
            },
            audio: {
                startTime: null,
                //语音录音中
                recording: false,
                //录音按钮展示
                visible: false
            },
            audioPlayer: {
                innerAudioContext: null,
                playingMessage: null,
            },
            videoPlayer: {
                visible: false,
                url: '',
                context: null
            },
            // 展示消息删除弹出框
            actionPopup: {
                visible: false,
                message: null,
                recallable: false,
            },
            // 消息选择
            messageSelector: {
                visible: false,
                messages: []
            },
            showPet: false,
            petInfo: {},
            id: null,
            // 默认搭子聊天列表 (type: default)
            chatList: [
                {
                    id: 1,
                    text: '刷到你的动态，发现我们想找的搭子类型挺像的，想问问你对活动强度有什么偏好吗？'
                },
                {
                    id: 2,
                    text: '看到你想找搭子，我对这方面也挺感兴趣的，想确认下你更看重搭子的什么特质呢？'
                },
                {
                    id: 3,
                    text: '看到你在找搭子，我也在找，想确认下你平时是喜欢提前规划还是即兴安排活动呢？'
                },
                {
                    id: 4,
                    text: '注意到你在找搭子，我这边时间比较灵活，想了解下你一般习惯在哪个区域活动呢？'
                },
                {
                    id: 5,
                    text: '刷到你找搭子的动态，感觉我们可能合得来，想了解下你对活动有什么要求吗？'
                },
            ],
            // 从活动详情向活动发起人发起的聊天 (type: activity)
            activityChatList: [
                {
                    id: 1,
                    text: '看到你发起的这个活动，感觉很有意思，想问问具体是几点开始呀？我怕路上耽误了赶不上。'
                },
                {
                    id: 2,
                    text: '注意到这个活动的地点我不太熟，想问下附近好停车吗？或者坐公交到哪站下比较方便？'
                },
                {
                    id: 3,
                    text: '刷到你组织的这个活动，我很想参加，可以向你更多活动细节嘛~'
                },
                {
                    id: 4,
                    text: '看到这个活动的介绍，有点心动，想确认下活动流程大概是怎样的，会不会有什么需要配合的环节？'
                },
            ],
            // 待审核发起的聊天 (type: pending)
            pendingChatList: [
                {
                    id: 1,
                    text: 'Hi~看到你的报名啦，有一些详细信息想跟你确认一下，方便审核，可以聊聊吗~'
                },
                {
                    id: 2,
                    text: '您好！关于您报名的活动，想和您确认并补充了解一些信息，请问现在是否方便交流一下？'
                },
                {
                    id: 3,
                    text: '您好！关于您申请活动报名，我们想进一步了解您的背景和想法，以确保这是一个适合您的活动。'
                },
                {
                    id: 4,
                    text: 'hello！欢迎你的报名！为了确保活动顺利进行并满足您的需求，我们想和您核对一下报名信息，方便嘛~'
                },
                {
                    id: 5,
                    text: '您好！为了做最终确认，我们需要和您沟通补充一些细节信息（例如：紧急联系人/饮食禁忌/设备情况等）。您现在可以交流一下吗？'
                },
            ],
            // 审核成功聊天 (type: success)
            successChatList: [
                {
                    id: 1,
                    text: 'Hi~看到你的报名啦，有一些详细信息想跟你确认一下，方便审核，可以聊聊吗~'
                },
                {
                    id: 2,
                    text: 'HI~你已成功加入我的活动，想问问你对活动有没有什么疑问或期待，我们可以提前沟通下。'
                },
                {
                    id: 3,
                    text: '恭喜你报名成功！随便聊两句，你平时参加这类活动，一般比较在意哪些细节呀？我们尽量安排得舒服点～'
                },
                {
                    id: 4,
                    text: '哈喽，审核过啦！想问问你对活动内容还有啥不清楚的不？趁现在有空，我一次性给你讲明白～'
                },
                {
                    id: 5,
                    text: '审核通过啦！活动前一天我会再发提醒给你，要是这段时间有啥变动，随时私信喊我就行，看到必回～'
                },
            ]
        }
    },
    computed: {
        // 根据聊天类型返回对应的聊天列表
        currentChatList() {
            switch (this.chatType) {
                case 'activity': // 从活动详情向活动发起人发起的聊天 (type: activity)
                    return this.activityChatList;
                case 'pending': // 待审核发起的聊天 (type: pending)
                    return this.pendingChatList;
                case 'success': // 审核成功聊天 (type: success)
                    return this.successChatList;
                case 'default':
                default:
                    return this.chatList;
            }
        }
    },
    async onLoad(options) {
        console.log(options, 'options')
        this.friendId = options.id;
        
        // 设置聊天类型，默认为default
        this.chatType = options.type || 'default';
        console.log('聊天类型:', this.chatType);
        
        // 首先恢复用户信息
        try {
            this.currentUser = uni.getStorageSync('currentUserInfo')
        } catch (e) {
            console.log('恢复用户信息失败:', e)
        }
        console.log(this.currentUser, 'this.currentUser in onLoad')
        
        await this.getPersonInfo(options.nickName, options.userAvatar)
        await this.$onLaunched;

        this.initialGoEasyListeners();
    },
    async onShow() {
         // 从本地存储恢复 currentUserInfo 到 store
         try {
            this.currentUser = uni.getStorageSync('currentUserInfo')
        } catch (e) {
            console.log('恢复用户信息失败:', e)
        }
        console.log(this.currentUser, 'this.currentUser')
        this.otherTypesMessagePanelVisible = false;
        this.emoji.visible = false;
    },
    onReady() {
        this.videoPlayer.context = uni.createVideoContext('videoPlayer', this);
        // https://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbartitle

    },
    onPullDownRefresh(e) {
        this.loadHistoryMessage(false);
    },
    onUnload() {
        //退出聊天页面之前，清空监听器
        this.goEasy.im.off(this.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, this.onMessageReceived);
        this.goEasy.im.off(this.GoEasy.IM_EVENT.MESSAGE_DELETED, this.onMessageDeleted);
    },
    methods: {
        handleSelectChatItem(item) {
            this.id = item.id;
            this.text = item.text;
        },
        handleSend() {
            this.sendTextMessage()
        },
        handleBack() {
            uni.navigateBack();
        },

        async getPersonInfo() {
            uni.showLoading({
                mask: true
            })
            const res = await getPersonInfo({
                userId: this.friendId
            })
            if (res.code == 200) {
                console.log(res.data, 'getPersonInfo')
                this.friend = res.data
                uni.setNavigationBarTitle({
                    title: this.friend.nickName
                })
                this.to = {
                    id: this.friend.userId,
                    type: this.GoEasy.IM_SCENE.PRIVATE,
                    data: {
                        name: this.friend.nickName,
                        avatar:this.friend.userAvatar
                    }
                };
                this.loadHistoryMessage(true);
            }
            uni.hideLoading()
        },

        //渲染文本消息，如果包含表情，替换为图片
        //todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
        renderTextMessage(message) {
            return '<span class="text-content" style="max-width: 274px;">' + this.emoji.decoder.decode(message.payload.text) + '</span>'
        },
        //像微信那样显示时间，如果有几分钟没发消息了，才显示时间
        //todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
        renderMessageDate(message, index) {
            if (index == 0) {
                return formatDate(message.timestamp)
            } else {
                if (message.timestamp - this.history.messages[index - 1].timestamp > 5 * 60 * 1000) {
                    return formatDate(message.timestamp)
                }
            }
            return '';
        },
        initialGoEasyListeners() {
            // 监听私聊消息
            this.goEasy.im.on(this.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, this.onMessageReceived);
            //监听消息删除
            this.goEasy.im.on(this.GoEasy.IM_EVENT.MESSAGE_DELETED, this.onMessageDeleted);
        },
        onMessageReceived(message) {
            let senderId = message.senderId;
            let receiverId = message.receiverId;
            console.log(message, this.currentUser, '1111')
            let friendId = this.currentUser.userId == senderId ? receiverId : senderId;
            if (friendId == this.friend.userId) {
                this.history.messages.push(message);

                // 如果收到的是对方发送的消息，重置发送限制状态
                if (message.senderId !== this.currentUser.userId) {
                    // 收到对方消息后，说明不再是第一次聊天
                    this.firstChat = false;
                    this.hasUnrepliedMessage = false;
                    this.lastSentMessageId = null;
                    this.canSendMessage = true;
                }

                //聊天时，收到消息标记为已读
                this.markPrivateMessageAsRead();
                //收到新消息，是滚动到最底部
                this.scrollToBottom();
            }
        },
        onMessageDeleted(deletedMessages) {
            deletedMessages.forEach(message => {
                let senderId = message.senderId;
                let receiverId = message.receiverId;
                let friendId = this.currentUser.userId == senderId ? receiverId : senderId;
                if (friendId == this.friend.userId) {
                    let index = this.history.messages.indexOf(message);
                    if (index > -1) {
                        this.history.messages.splice(index, 1);
                    }
                }
            });
        },
        /**
         * 核心就是设置高度，产生明确占位
         *
         * 小  (宽度和高度都小于预设尺寸)
         *    设高=原始高度
         * 宽 (宽度>高度)
         *    高度= 根据宽度等比缩放
         * 窄  (宽度<高度)或方(宽度=高度)
         *    设高=MAX height
         *
         * @param width,height
         * @returns number
         */
        getImageHeight(width, height) {
            if (width < IMAGE_MAX_WIDTH && height < IMAGE_MAX_HEIGHT) {
                return height * 2;
            } else if (width > height) {
                return (IMAGE_MAX_WIDTH / width * height) * 2;
            } else if (width == height || width < height) {
                return IMAGE_MAX_HEIGHT * 2;
            }
        },
        sendMessage(message) {
            console.log(message, 'message');
            this.history.messages.push(message);

            this.scrollToBottom();
            this.goEasy.im.sendMessage({
                message: message,
                onSuccess: (message) => {
                    console.log('发送成功.', message);
                    // 发送成功后，不再是第一次聊天
                    this.firstChat = false;
                },
                onFailed: (error) => {
                    if (error.code == 507) {
                        console.log(
                            '发送语音/图片/视频/文件失败，没有配置OSS存储，详情参考：https://www.goeasy.io/cn/docs/goeasy-2.x/im/message/media/send-media-message.html'
                        );
                    } else {
                        console.log('发送失败:', error);
                    }
                }
            });
        },
        sendTextMessage() {
            // 检查是否可以发送消息
            console.log(this.canSendMessage, 'sendTextMessage')
            if (!this.canSendMessage) {
                uni.showToast({
                    title: '对方未回复你之前，只能发送一条消息',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }

            if (this.text.trim() !== '') {
                let body = this.text;
                console.log(this.text, 'this.text');
                if (this.text.length >= 50) {
                    body = this.text.substring(0, 30) + '...';
                }
                this.goEasy.im.createTextMessage({
                    text: this.text,
                    to: this.to,
                    notification: {
                        title: this.currentUser.name + '发来一段文字',
                        body: body
                    },
                    onSuccess: (message) => {
                        this.sendMessage(message);
                        // 发送成功后，如果是第一次聊天，立即更新状态
                        if (this.firstChat) {
                            this.firstChat = false;
                        }
                        // 发送成功后，重新检查消息限制状态
                        this.checkUnrepliedMessage();
                    },
                    onFailed: (e) => {
                        console.log('error :', e);
                    }
                });
            }
            this.text = '';
        },
        sendImageMessage() {
            // 检查是否可以发送消息
            if (!this.canSendMessage) {
                uni.showToast({
                    title: '对方未回复你之前，只能发送一条消息',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }

            const that = this
            uni.chooseImage({
                count: 1,
                success: (res) => {
                    res.tempFilePaths.forEach(async file => {
                        const res1 = await that.$utils.uploadFile(file)
                        console.log(777, res1);
                        if (res1.code == 200) {
                            var msg_img = {
                                url: res1.full_url
                            }
                            this.goEasy.im.createCustomMessage({
                                type: 'img', //字符串，可以任意自定义类型，比如红包'hongbao', 订单'order，处方'chufang'
                                payload: msg_img,
                                to: this.to,
                                notification: {
                                    title: this.currentUser.userName + '发来一张图片',
                                    body: '[图片消息]' // 字段最长 50 字符
                                },
                                onProgress: function (progress) {
                                    console.log(progress)
                                },
                                onSuccess: (message) => {
                                    console.log(111, message);
                                    this.sendMessage(message);
                                    // 发送成功后，如果是第一次聊天，立即更新状态
                                    if (this.firstChat) {
                                        this.firstChat = false;
                                    }
                                    // 发送成功后，重新检查消息限制状态
                                    this.checkUnrepliedMessage();
                                },
                                onFailed: (e) => {
                                    console.log('error :', e);
                                }
                            });
                        }
                    })
                }
            });
        },
        sendpetMessage() {
            // 检查是否可以发送消息
            if (!this.canSendMessage) {
                uni.showToast({
                    title: '对方未回复你之前，只能发送一条消息',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }

            this.goEasy.im.createCustomMessage({
                type: 'pet',
                payload: this.petInfo,
                to: this.to,
                notification: {
                    title: this.currentUser.userName + '发来一个宠物',
                    body: '[宠物消息]'
                },
                onSuccess: (message) => {
                    //this.otherTypesMessagePanelVisible = false;
                    this.sendMessage(message);
                    // 发送成功后，如果是第一次聊天，立即更新状态
                    if (this.firstChat) {
                        this.firstChat = false;
                    }
                    // 发送成功后，重新检查消息限制状态
                    this.checkUnrepliedMessage();
                },
                onFailed: (e) => {
                    console.log('error :', e);
                }
            });
        },
        // sendOrderMessage(order) {
        //     //GoEasyIM自定义消息,实现订单发送
        //     console.log(order);
        //     //return false
        //     this.goEasy.im.createCustomMessage({
        //         type: 'order',
        //         payload: order,
        //         to: this.to,
        //         notification: {
        //             title: this.currentUser.userName + '发来一个宠物',
        //             body: '[宠物消息]'
        //         },
        //         onSuccess: (message) => {
        //             this.otherTypesMessagePanelVisible = false;
        //             this.sendMessage(message);
        //         },
        //         onFailed: (e) => {
        //             console.log('error :', e);
        //         }
        //     });
        //     this.orderList.visible = false;
        // },
        showActionPopup(message) {
            const MAX_RECALLABLE_TIME = 3 * 60 * 1000; //3分钟以内的消息才可以撤回
            this.messageSelector.messages = [message];
            if ((Date.now() - message.timestamp) < MAX_RECALLABLE_TIME && message.senderId == this.currentUser.userId &&
                message.status == 'success') {
                this.actionPopup.recallable = true;
            } else {
                this.actionPopup.recallable = false;
            }
            this.actionPopup.visible = true;
        },
        hideActionPopup() {
            this.actionPopup.visible = false;
            this.actionPopup.message = null;
        },
        deleteSingleMessage() {
            this.actionPopup.visible = false;
            this.deleteMessage();
            // uni.showModal({
            // 	content: '确认删除？',
            // 	success: (res) => {
            // 		this.actionPopup.visible = false;
            // 		if (res.confirm) {
            // 			this.deleteMessage();
            // 		}
            // 	},
            // })
        },
        deleteMultipleMessages() {
            if (this.messageSelector.messages.length > 0) {
                uni.showModal({
                    content: '确认删除？',
                    success: (res) => {
                        this.messageSelector.visible = false;
                        if (res.confirm) {
                            this.deleteMessage();
                        }
                    },
                })
            }
        },
        deleteMessage() {
            this.goEasy.im.deleteMessage({
                messages: this.messageSelector.messages,
                onSuccess: (result) => {
                    this.messageSelector.messages.forEach(message => {
                        let index = this.history.messages.indexOf(message);
                        if (index > -1) {
                            this.history.messages.splice(index, 1);
                        }
                    });
                    this.messageSelector.messages = [];
                },
                onFailed: (error) => {
                    console.log('error:', error);
                }
            });
        },
        recallMessage() {
            this.actionPopup.visible = false;
            this.goEasy.im.recallMessage({
                messages: this.messageSelector.messages,
                onSuccess: () => {
                    console.log('撤回成功');
                },
                onFailed: (error) => {
                    console.log('撤回失败,error:', error);
                }
            });
        },
        editRecalledMessage(text) {
            if (this.audio.visible) {
                this.audio.visible = false;
            }
            this.text = text;
        },
        showCheckBox() {
            this.messageSelector.messages = [];
            this.messageSelector.visible = true;
            this.actionPopup.visible = false;
        },
        hideCheckBox() {
            this.messageSelector.messages = [];
            this.messageSelector.visible = false;
            this.actionPopup.visible = false;
        },
        selectMessages(e) {
            const selectedMessageIds = e.detail.value;
            let selectedMessages = [];
            this.history.messages.forEach(message => {
                if (selectedMessageIds.includes(message.messageId)) {
                    selectedMessages.push(message);
                }
            })
            this.messageSelector.messages = selectedMessages;
        },
        allCheckbox() {
            if (this.messageSelector.messages.length == this.history.messages.length) {
                this.messageSelector.messages = []
            } else {
                let selectedMessages = [];
                this.history.messages.forEach(message => {
                    selectedMessages.push(message);
                })
                this.messageSelector.messages = selectedMessages;
            }
        },
        loadHistoryMessage(scrollToBottom) { //历史消息
            console.log('开始加载历史消息:', {
                friendUserId: this.friend.userId,
                currentUserId: this.currentUser?.userId,
                friendId: this.friendId,
                friend: this.friend,
                scrollToBottom: scrollToBottom
            });
            
            this.history.loading = true;
            let lastMessageTimeStamp = null;
            let lastMessage = this.history.messages[0];
            if (lastMessage) {
                lastMessageTimeStamp = lastMessage.timestamp;
            }
            
            if (!this.friend.userId) {
                console.error('friend.userId 为空，无法加载历史消息');
                this.history.loading = false;
                return;
            }
            
            this.goEasy.im.history({
                userId: this.friend.userId,
                lastTimestamp: lastMessageTimeStamp,
                limit: 10,
                onSuccess: (result) => {
                    console.log('历史消息加载成功:', result, this.history, 'result');
                    uni.stopPullDownRefresh();
                    this.history.loading = false;
                    let messages = result.content;
                    console.log('获取到的历史消息数量:', messages.length);
                    
                    if (messages.length == 0) {
                        this.history.allLoaded = true;
                        // 如果没有历史消息，说明是第一次聊天
                        this.firstChat = true;
                        console.log('没有历史消息，设置为第一次聊天');
                    } else {
                        // 有历史消息，说明不是第一次聊天
                        this.firstChat = false;
                        console.log('有历史消息，不是第一次聊天');

                        if (lastMessageTimeStamp) {
                            this.history.messages = messages.concat(this.history.messages);
                        } else {
                            this.history.messages = messages;
                        }
                        if (messages.length < 10) {
                            this.history.allLoaded = true;
                        }
                        
                        // 每次加载历史消息后都检查消息限制状态
                        this.checkUnrepliedMessage();
                        
                        if (scrollToBottom) {
                            this.scrollToBottom();
                            //收到的消息设置为已读
                            this.markPrivateMessageAsRead();
                        }
                    }
                },
                onFailed: (error) => {
                    //获取失败
                    console.error('获取历史消息失败:', error);
                    uni.stopPullDownRefresh();
                    this.history.loading = false;
                }
            });
        },
        //语音录制按钮和键盘输入的切换
        switchAudioKeyboard() {
            this.audio.visible = !this.audio.visible;
            if (uni.authorize) {
                uni.authorize({
                    scope: 'scope.record',
                    fail: () => {
                        uni.showModal({
                            title: '获取录音权限失败',
                            content: '请先授权才能发送语音消息！'
                        });
                    }
                });
            }
        },
        onRecordStart() {
            try {
                recorderManager.start();
            } catch (e) {
                uni.showModal({
                    title: '录音错误',
                    content: '请在app和小程序端体验录音，Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档'
                });
            }
        },
        onRecordEnd() {
            try {
                recorderManager.stop();
            } catch (e) {
                console.log(e);
            }
        },
        showImageFullScreen(e) {
            let imagesUrl = [this.api_host + e.currentTarget.dataset.url];
            uni.previewImage({
                urls: imagesUrl
            });
        },
        playVideo(e) {
            this.videoPlayer.visible = true;
            this.videoPlayer.url = e.currentTarget.dataset.url;
            this.$nextTick(() => {
                this.videoPlayer.context.requestFullScreen({
                    direction: 0
                });
                this.videoPlayer.context.play();
            });
        },
        playAudio(audioMessage) {
            let playingMessage = this.audioPlayer.playingMessage;

            if (playingMessage) {
                this.audioPlayer.innerAudioContext.stop();
                // 如果点击的消息正在播放，就认为是停止播放操作
                if (playingMessage == audioMessage) {
                    return;
                }
            }
            this.audioPlayer.playingMessage = audioMessage;
            this.audioPlayer.innerAudioContext.src = audioMessage.payload.url;
            this.audioPlayer.innerAudioContext.play();
        },
        onVideoFullScreenChange(e) {
            //当退出全屏播放时，隐藏播放器
            if (this.videoPlayer.visible && !e.detail.fullScreen) {
                this.videoPlayer.visible = false;
                this.videoPlayer.context.stop();
            }
        },
        messageInputFocusin() {
            this.otherTypesMessagePanelVisible = false;
            this.emoji.visible = false;
        },
        switchEmojiKeyboard() {
            if (!this.canSendMessage) {
                return;
            }
            this.emoji.visible = !this.emoji.visible;
            this.otherTypesMessagePanelVisible = false;
        },
        showOtherTypesMessagePanel() {
            if (!this.canSendMessage) {
                return;
            }
            this.otherTypesMessagePanelVisible = !this.otherTypesMessagePanelVisible;
            this.emoji.visible = false;
        },
        chooseEmoji(emojiKey) {
            if (!this.canSendMessage) {
                return;
            }
            this.text += emojiKey;
        },
        showOrderMessageList() {
            this.orderList.visible = true;
        },
        hideOrderMessageList() {
            this.orderList.visible = false;
        },
        scrollToBottom() {
            this.$nextTick(() => {
                uni.pageScrollTo({
                    scrollTop: 2000000,
                    duration: 0
                });
            });
        },
        markPrivateMessageAsRead() {
            this.goEasy.im.markMessageAsRead({
                id: this.to.id,
                type: this.to.type,
                onSuccess: function () {
                    console.log('标记私聊已读成功');
                },
                onFailed: function (error) {
                    console.log("标记私聊已读失败", error);
                }
            });
        },
        checkUnrepliedMessage() {
            console.log('检查未回复消息状态', {
                firstChat: this.firstChat,
                messagesLength: this.history.messages.length,
                currentUserId: this.currentUser.userId
            });

            // 如果是第一次聊天，允许发送消息
            if (this.firstChat) {
                this.hasUnrepliedMessage = false;
                this.lastSentMessageId = null;
                this.canSendMessage = true;
                return;
            }

            // 如果有历史聊天记录（双方都有对话），则取消限制
            if (this.history.messages.length > 0) {
                // 检查是否有对方的消息（即是否有过对话）
                const hasFriendMessage = this.history.messages.some(msg => msg.senderId != this.currentUser.userId);
                const hasUserMessage = this.history.messages.some(msg => msg.senderId == this.currentUser.userId);
                
                if (hasFriendMessage && hasUserMessage) {
                    // 双方都有消息，说明有过对话，取消限制
                    console.log('双方有过对话，取消发送限制');
                    this.hasUnrepliedMessage = false;
                    this.lastSentMessageId = null;
                    this.canSendMessage = true;
                    return;
                }
                
                // 只有用户消息，没有对方回复的情况
                if (!hasFriendMessage && hasUserMessage) {
                    const userMessages = this.history.messages.filter(msg => msg.senderId == this.currentUser.userId);
                    if (userMessages.length >= 1) {
                        // 用户已发送至少一条消息但对方未回复，限制发送
                        console.log('限制发送: 用户已发送>=1条消息但对方未回复');
                        this.hasUnrepliedMessage = true;
                        this.lastSentMessageId = userMessages[userMessages.length - 1].messageId;
                        this.canSendMessage = false;
                    } else {
                        // 尚未发送消息，可以发送
                        console.log('允许发送: 用户发送消息数量为0');
                        this.hasUnrepliedMessage = false;
                        this.lastSentMessageId = null;
                        this.canSendMessage = true;
                    }
                } else {
                    // 其他情况，允许发送
                    this.hasUnrepliedMessage = false;
                    this.lastSentMessageId = null;
                    this.canSendMessage = true;
                }
            } else {
                // 没有历史消息，可以正常发送
                this.hasUnrepliedMessage = false;
                this.lastSentMessageId = null;
                this.canSendMessage = true;
            }

            console.log('最终状态:', {
                canSendMessage: this.canSendMessage,
                hasUnrepliedMessage: this.hasUnrepliedMessage,
                firstChat: this.firstChat
            });
        }
    }
}
</script>

<style lang="scss" scoped>
@import '../../static/style/common.css';

.chatInterface {
    background: #F7F6FF;
}

.scroll-view {
    min-height: 100vh;
    background: #F7F6FF !important;
}

.text-content {
    background: #319EFF !important;
    color: #fff !important;
}

.pet-msg {
    width: 100%
}

.message-tip {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    background: rgba(255, 67, 67, 0.08);
    border: 1px solid rgba(255, 67, 67, 0.2);
    border-radius: 16px;
    font-size: 14px;
    color: #FF4343;
    box-sizing: border-box;
    text-align: center;
    margin: 10px 20px;
    box-shadow: 0 2px 8px rgba(255, 67, 67, 0.1);

    .tip-icon {
        width: 20px;
        height: 20px;
        margin-right: 4px;
    }
}

.disabled {
    opacity: 0.5;
    pointer-events: none;
}

.consult-input:disabled {
    background-color: #f5f5f5;
    color: #999;
}


.block_2 {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    background: url(https://hxs.dsjhs.com:553/prod-api/profile/dazhaohu-head.png) 100% no-repeat;
    background-size: 100% 100%;
    padding: 19px 16px 28px 16px;
    box-sizing: border-box;

    .text_3 {
        overflow-wrap: break-word;
        color: rgba(52, 49, 79, 1);
        font-size: 18px;
        font-family: PingFangSC-Medium;
        font-weight: 500;
        text-align: left;
        white-space: nowrap;
        line-height: 25px;
        margin: 0 132px 0 58px;
    }

    .text-wrapper_1 {
        background-color: rgba(247, 247, 247, 1);
        border-radius: 20px 20px 0px 20px;
        margin-top: 12px;
        padding: 10px 16px 10px 16px;
        border: 1px solid transparent;

        &.active-chat {
            border: 1px solid rgba(123, 67, 194, 1);
        }

        .text_4 {
            width: 326px;
            overflow-wrap: break-word;
            color: rgba(52, 49, 79, 1);
            font-size: 16px;
            font-weight: normal;
            text-align: left;
            line-height: 22px;
        }
    }

    .box_3 {
        width: 358px;
        margin-top: 28px;

        .text-wrapper_6 {
            color: #34314F;
            background: #F7F7F7;
            border-radius: 20px;
            padding: 13px 43px 13px 43px;

            .text_9 {
                overflow-wrap: break-word;
                color: rgba(52, 49, 79, 1);
                font-size: 16px;
                font-family: PingFangSC-Semibold;
                font-weight: 600;
                text-align: right;
                white-space: nowrap;
                line-height: 22px;
            }
        }

        .text-wrapper_7 {
            // background: url(https://lanhu-oss-proxy.lanhuapp.com/SketchPng176b07802458a086e9b5bf7cb4d98343e41128640f7eeba1b61267ecc203711a) 100% no-repeat;
            background: linear-gradient(173deg, #FFA5F5 0%, #319EFF 100%);
            border-radius: 20px;
            background-size: 100% 100%;
            padding: 13px 89px 13px 89px;

            .text_10 {
                overflow-wrap: break-word;
                color: rgba(255, 255, 255, 1);
                font-size: 16px;
                font-family: PingFangSC-Semibold;
                font-weight: 600;
                text-align: right;
                white-space: nowrap;
                line-height: 22px;
            }
        }
    }

    .image_3 {
        position: absolute;
        left: 15px;
        top: -9px;
        width: 50px;
        height: 50px;
    }
}
</style>